package com.tanhua.dubbo.api;
import cn.hutool.core.collection.CollUtil;
import com.tanhua.model.mongo.UserLike;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.List;

@DubboService
public class UserLikeApiImpl implements UserLikeApi{

    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public Boolean saveOrUpdate(Long userId, Long likeUserId, boolean isLike) {
        try {
            //1、查询数据
            Query query = Query.query(Criteria.where("userId").is(userId).and("likeUserId").is(likeUserId));
            UserLike userLike = mongoTemplate.findOne(query, UserLike.class);
            //2、如果不存在，保存
            if(userLike == null) {
                userLike = new UserLike();
                userLike.setUserId(userId);
                userLike.setLikeUserId(likeUserId);
                userLike.setCreated(System.currentTimeMillis());
                userLike.setUpdated(System.currentTimeMillis());
                userLike.setIsLike(isLike);
                mongoTemplate.save(userLike);
            }else {
                //3、更新
                Update update = Update.update("isLike", isLike)
                        .set("updated",System.currentTimeMillis());
                mongoTemplate.updateFirst(query,update,UserLike.class);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public List<UserLike> findByUserId(Integer page, Integer pagesize, Long userId) {
        return null;
    }

    //查询我喜欢的数量
    @Override
    public Long findLoverCount(Long id) {
        //判断isLike不为false
        List<UserLike> userLikeList = this.mongoTemplate.find(Query.query(Criteria.where("userId").is(id)), UserLike.class);
        List<UserLike> user = new ArrayList<>();
        for (UserLike userLike : userLikeList) {
            if (userLike.getIsLike() != false){
                user.add(userLike);
            }
        }
        Long count = 0l;
        for (UserLike userLike : user) {
            Long userId = userLike.getUserId();
            count++;
        }
        return count;
    }

    @Override
    public Long findEachLoveCount(Long id) {
        //查询互相喜欢的数量
        List<UserLike> likeList = mongoTemplate.find(Query.query(Criteria.where("userId").is(id).and("isLike").is(true)), UserLike.class);
        List<Long> likeUserId = CollUtil.getFieldValues(likeList, "likeUserId", Long.class);
        Long count = 0L;
        for (Long likeUid : likeUserId) {
            UserLike one = mongoTemplate.findOne(Query.query(Criteria.where("userId").is(likeUid).and("likeUserId").is(id).and("isLike").is(true)), UserLike.class);
            if (one!=null){
                count=count+1L;
            }

        }
        return count;

    }

    @Override
    public Long findFanCount(Long id) {
        return mongoTemplate.count(Query.query(Criteria.where("likeUserId").is(id).and("isLike").is(true)),UserLike.class);
    }

    //我喜欢的列表
    @Override
    public List findLoverUsers(Long userId, Integer page, Integer pagesize) {
        List<UserLike> list = this.queryList(Query.query(Criteria.where("userId").is(userId).and("isLike").nin(false)), page, pagesize);
        return list;
    }

    // 互相喜欢列表
    @Override
    public List findEachLikeUsers(Long userId, Integer page, Integer pageSize) {
        //我喜欢
        List<UserLike> userLikeList = this.mongoTemplate.find(Query.query(Criteria.where("userId").is(userId).and("isLike").nin(false)), UserLike.class);
        List<Long> likeUserIdList = new ArrayList<>();

        for (UserLike userLike : userLikeList) {
            likeUserIdList.add(userLike.getUserId());
        }
        //喜欢我
        List<UserLike> list = queryList(Query.query(Criteria.where("likeUserId").is(likeUserIdList).and("isLike").nin(false)), page, pageSize);

        return list;
    }

    //查询粉丝列表
    @Override
    public List findFanUsers(Long userId, Integer page, Integer pageSize) {
        List<UserLike> list = this.queryList(Query.query(Criteria.where("likeUserId").is(userId)), page, pageSize);
        return list;
    }

    private List queryList(Query query, Integer page, Integer pagesize) {
        PageRequest pageRequest = PageRequest.of(page - 1, pagesize, Sort.by(Sort.Order.desc("created")));
        query.with(pageRequest);
        List<UserLike> userLikeList = this.mongoTemplate.find(query, UserLike.class);

        return userLikeList;
    }

    //userId前端传递的ID
    //id当前登录用户ID
    //（取消喜欢）
    @Override
    public void likeid(Long id, Long userId) {
        Query query = Query.query(Criteria.where("userId").is(id).and("likeUserId").is(userId));

        mongoTemplate.remove(query , UserLike.class);

    }

    //（喜欢粉丝）创建UserLike存入
    @Override
    public void fansid(Long id, Long userId) {
        UserLike userLike = new UserLike();

        userLike.setId(ObjectId.get());
        userLike.setCreated(System.currentTimeMillis());
        userLike.setUpdated(System.currentTimeMillis());
        userLike.setUserId(id);
        userLike.setLikeUserId(userId);
    }

    @Override
    public List<Long> findMyLike(Integer page, Integer pageSize, Long userId) {
        Query query =Query.query(Criteria.where("userId").is(userId).and("isLike").is(true));
        query.skip((page-1)*pageSize).limit(pageSize).with(Sort.by(Sort.Order.desc("created")));
        List<UserLike> userLikes = mongoTemplate.find(query, UserLike.class);
        List<Long> friendId = CollUtil.getFieldValues(userLikes, "likeUserId", Long.class);
        return friendId;
    }

    @Override
    public List<Long> findLikeYou(Integer page, Integer pageSize, Long userId) {
        Query query =Query.query(Criteria.where("likeUserId").is(userId).and("isLike").is(true));
        query.skip((page-1)*pageSize).limit(pageSize).with(Sort.by(Sort.Order.desc("created")));
        List<UserLike> userLikes = mongoTemplate.find(query, UserLike.class);
        List<Long> friendId = CollUtil.getFieldValues(userLikes, "userId", Long.class);
        return friendId;
    }

    @Override
    public UserLike hasLove(Long currentUserId, Long id) {
        UserLike one = mongoTemplate.findOne(Query.query(Criteria.where("userId").is(currentUserId).and("likeUserId").is(id)), UserLike.class);
        return one;
    }

    @Override
    public void saveLoveStatus(UserLike userLike) {
        mongoTemplate.insert(userLike);
    }

    @Override
    public void updateLoveStatus(UserLike userLike) {
        Query query =Query.query(Criteria.where("userId").is(userLike.getUserId()).and("likeUserId").is(userLike.getLikeUserId()));
        Update update = new Update();
        update.set("isLike",userLike.getIsLike());
        mongoTemplate.updateFirst(query,update,UserLike.class);
    }

    @Override
    public UserLike findOne(Long userId, Long uid) {
        Query query = Query.query(Criteria.where("userId").is(userId).and("likeUserId").is(uid));
        UserLike one = mongoTemplate.findOne(query, UserLike.class);
        return one;
    }
}
